// import mqtt from "mqtt"
import * as mqtt from 'mqtt/dist/mqtt.min'
import useUserStore from '@/store/modules/user'

import { reactive, ref, onMounted, onUnmounted, nextTick, } from "vue"
import router from '@/router/index'
// const router = useRouter()
import options from "./config"
import {
    ElMessage,
    ElLoading,
    ElMessageBox,
    ElNotification,
} from "element-plus"
let socket = null // 连接对象
let linkFailCount = 0 // 连接次数，目前连接三次
let relinkLoading = null // 重连全屏loading
function useMqtt(topic) {
    const data = ref()
    const connection = reactive({
        clean: true,
        clientId: "IOT_Platform_" + Math.random().toString(16).substring(2, 8),
        connectTimeout: 30 * 1000, // ms,
        host: "183.92.128.122",
        password: "Sgj808606",
        port: 8083,
        endpoint: "/mqtt",
        protocol: "ws",
        reconnectPeriod: 4000, // ms
        username: "pureut",
    })
    const tpc = topic

    //订阅信息设置
    const subscription = ref({
        topic: topic, //需要动态配置
        qos: 2,
    })
    let client = ref({ connected: false })
    const receivedMessages = ref("")
    const subscribedSuccess = ref(false)
    const btnLoadingType = ref("")
    const retryTimes = ref(0)

    //初始化
    const initData = () => {
        client.value = {
            connected: false,
        }

        retryTimes.value = 0
        btnLoadingType.value = ""
        subscribedSuccess.value = false
        nextTick(() => {
            createConnection()
            doSubscribe()
        })
        // createConnection()
        // doSubscribe()
    }

    const handleOnReConnect = () => {
        retryTimes.value += 1
        // loading()
        if (retryTimes.value > 5) {
            try {
                client.value.end()
                initData()
                console.log("connection maxReconnectTimes limit, stop retry")
            } catch (error) {
                console.log("handleOnReConnect catch error:", error)
            }
        }
    }

    // 创建连接
    const createConnection = () => {

        try {
            btnLoadingType.value = "connect"
            const { protocol, host, port, endpoint, ...options } = connection
            const connectUrl = `${protocol}://${host}:${port}${endpoint}`
            // console.log(connectUrl, 'connectUrl')
            client.value = mqtt.connect(connectUrl, options)
            if (client.value.on) {
                linkFailCount = 0 // 打开连接，连接次数改为0

                client.value.on("connect", () => {
                    // 加载动画如果开启，则关闭
                    if (relinkLoading) {
                        relinkLoading.close()
                    }
                    btnLoadingType.value = ""
                    // if (router.currentRoute.value.fullPath == '/index') {
                    ElNotification({
                        title: "消息提醒",
                        type: "success",
                        message: `连接服务成功`,
                    })
                    // }

                    // console.log("connection successful")
                })
                client.value.on("reconnect", handleOnReConnect)
                client.value.on("error", (error) => {
                    ElMessageBox.confirm("连接失败，是否尝试刷新？", "警告" + error, {
                        confirmButtonText: "刷新",
                        cancelButtonText: "取消",
                        type: "warning",
                        "close-on-click-modal": false,
                    }).then((e) => {
                        if (e == "confirm") {
                            location.reload()
                        }
                    })
                    console.log("connection error:", error)
                })
                console.log(tpc, client.value, 'topic')

                client.value.on("message", (topic, message) => {
                    console.log('message', JSON.parse(message), topic, tpc, 'message')
                    data.value = JSON.parse(message) //将接收的message JSON对象转成js对象
                    let regex = /info/
                    if (regex.test(topic)) {
                        ElNotification({
                            title: data.value.createTime,
                            message: data.value.message_content,
                            duration: 2000
                        })
                    }

                    if (topic == '/device/gather') {
                        console.log('message', JSON.parse(message))
                        useUserStore().getGather(data.value)

                    } else {
                        if (topic != tpc) {
                            return
                        }
                        useUserStore().getMonitoring(data.value)
                    }


                })
            }
        } catch (error) {
            btnLoadingType.value = ""
            console.log("mqtt.connect error:", error)
        }
    }
    /**
     * 
     * 取消订阅 
     */
    const unubscribe = () => {
        btnLoadingType.value = "unubscribe"
        const { topic, qos } = subscription.value
        client.value.unubscribe(topic, { qos }, (error, granted) => {
            console.log('Unsubscribed')
        })
        console.log('unubscribe======', client.value);
        // client.value.unubscribe('testtopic', () => {
        //     console.log('Unsubscribed')
        // })
    }
    const toLink = (r) => {
        console.log(r, 'r')
        try {
            if (r.isSkip == 1) {
                router.push(r.url)
            }
            // router.push(url)
            // console.log(m, 'm')
            // router.push('/contractSigning/all/await-examine')
        } catch (err) {
            console.log(err)
        }


        // console.log('----------', url)
    }
    //订阅消息
    const doSubscribe = () => {

        btnLoadingType.value = "subscribe"
        const { topic, qos } = subscription.value
        console.log();
        client.value.subscribe(topic, { qos }, (error, granted) => {
            btnLoadingType.value = ""
            if (error) {
                console.log("subscribe error:", error)
                ElNotification({
                    title: "消息提醒",
                    type: "error",
                    message: "连接服务失败=> " + error,
                })
                return
            }
            subscribedSuccess.value = true
            console.log("subscribe successfully:", granted)
        })
    }

    //关闭连接
    const destroyConnection = () => {

        if (client.value.connected) {
            btnLoadingType.value = "disconnect"
            try {
                client.value.end(false, () => {
                    client.value = {
                        connected: false,
                    }

                    retryTimes.value = 0
                    btnLoadingType.value = ""
                    subscribedSuccess.value = false
                    console.log("disconnected successfully")
                })
            } catch (error) {
                btnLoadingType.value = ""
                console.log("disconnect error:", error)
            }
        }
    }

    onMounted(() => {
        window.toLink = toLink

    })
    // //组件销毁前断开连接
    onUnmounted(() => {
        console.log("页面销毁前断开连接------")
        destroyConnection()
    })
    return { data: data.value, connection, subscription, destroyConnection, initData, unubscribe }
}


/**
 * 断开立即重连
 */
const reconnection = () => {
    // 连接关闭时，立刻开启重连机制
    ElMessageBox.confirm("连接失败，是否尝试刷新？", "警告", {
        confirmButtonText: "刷新",
        cancelButtonText: "取消",
        type: "warning",
        "close-on-click-modal": false,
    }).then((e) => {
        if (e == "confirm") {
            location.reload()
        }
    })
}
export default useMqtt
